/**
 * 
 */
package com.kstech.test.wqc.communication;

import android.util.Log;

import com.kstech.test.wqc.utils.AppContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


/**
 * 与检验终端的的链接对象
 *
 * @author zhaopuqing
 * @created 2016-10-19 下午3:58:45
 * @since v1.0
 */
public class Connection {

	/**
	 * Tcp服务器（检测终端）侦听端口号
	 */
	private final static int SERVER_PORT = 4001;

	/**
	 * 链接是否已经中断，TRUE:已经中断 FALSE：未中断
	 */
	private boolean interrupted;

	private Socket socket;

	private static Connection conn;

	private Connection() {
		try {
			socket = new Socket("192.168.0.178", SERVER_PORT);
			this.interrupted = false;
		} catch (Exception e) {
//			throw new RuntimeException("创建TCP链接失败[IP:" + AppContext.getCurrentCheckLine().getIp()
//					+ ",PORT:" + SERVER_PORT + "]", e);
			Log.e("", "创建TCP链接失败[IP:" + "192.168.0.178"
					+ ",PORT:" + SERVER_PORT + "]");
		}
	}

	public static boolean isConnInterrupted(){
		return conn==null||conn.isInterrupted();
	}

	/**
	 * 建立链接
	 */
	public static Connection getConnection() {
		if (conn == null || conn.isInterrupted()) {
			conn = new Connection();
		}
		return conn;
	}

	/**
	 * 关闭当前链接
	 */
	public void close() {
		try {
			interrupted = true;
			if (socket != null) {
				socket.close();
				socket = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取输入流
	 *
	 * @return
	 */
	public InputStream getIn() {
		try {
			return socket == null ? null : socket.getInputStream();
		} catch (IOException e) {
			throw new RuntimeException("获取TCP输入流失败[IP:" + "192.168.0.178"
					+ ",PORT:" + SERVER_PORT + "]", e);
		}
	}

	/**
	 * 获取输出流
	 *
	 * @return
	 */
	public OutputStream getOut() {
		try {
			return socket == null ? null : socket.getOutputStream();
		} catch (IOException e) {
			throw new RuntimeException("获取TCP输出流失败[IP:" + "192.168.0.178"
					+ ",PORT:" + SERVER_PORT + "]", e);
		}
	}

	/**
	 * 判断当前链接是否中断
	 *
	 * @return
	 */
	public boolean isInterrupted() {
		return interrupted || socket == null;
	}

	/**
	 * 设置链接状态为中断
	 */
	public void setToInterrupted() {
		this.interrupted = false;
	}

}
